<template>
  <div class="ward-management-page">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon :size="40"><OfficeBuilding /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">病房总数</div>
              <div class="stat-value">{{ wardStats.totalWards }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon beds">
              <el-icon :size="40"><Grid /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">床位总数</div>
              <div class="stat-value">{{ wardStats.totalBeds }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon occupied">
              <el-icon :size="40"><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">已占用床位</div>
              <div class="stat-value">{{ wardStats.occupiedBeds }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 病房列表 -->
    <el-card shadow="never" class="ward-list-card">
      <!-- 操作栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-input
            v-model="searchText"
            placeholder="搜索病房名称或编号"
            :prefix-icon="Search"
            style="width: 300px"
            clearable
            @input="handleSearch"
          />
        </div>
        <div class="toolbar-right">
          <el-button type="primary" :icon="Plus" @click="handleAddWard">
            添加病房
          </el-button>
          <el-button :icon="Refresh" @click="fetchWardList">刷新</el-button>
        </div>
      </div>

      <!-- 病房列表 -->
      <div v-loading="loading" class="ward-list">
        <el-empty v-if="!loading && wardList.length === 0" description="暂无病房数据" />
        
        <div
          v-for="ward in wardList"
          :key="ward._id"
          class="ward-item"
        >
          <el-card shadow="hover" class="ward-card">
            <!-- 病房头部 -->
            <div class="ward-header">
              <div class="ward-info">
                <h3 class="ward-name">
                  <el-icon><OfficeBuilding /></el-icon>
                  {{ ward.wardName }}
                </h3>
                <div class="ward-details">
                  <el-tag v-if="ward.wardNumber" size="small" type="info">
                    编号：{{ ward.wardNumber }}
                  </el-tag>
                  <el-tag v-if="ward.building" size="small" type="info">
                    {{ ward.building }}
                  </el-tag>
                  <el-tag v-if="ward.floor" size="small" type="info">
                    {{ ward.floor }}层
                  </el-tag>
                  <span class="bed-stats">
                    床位：{{ ward.occupiedCount || 0 }}/{{ ward.bedCount || 0 }}
                  </span>
                </div>
              </div>
              <div class="ward-actions">
                <el-button
                  type="primary"
                  :icon="Plus"
                  size="small"
                  @click="handleAddBed(ward)"
                >
                  添加床位
                </el-button>
                <el-button
                  :icon="Edit"
                  size="small"
                  @click="handleEditWard(ward)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  :icon="Delete"
                  size="small"
                  @click="handleDeleteWard(ward)"
                >
                  删除
                </el-button>
              </div>
            </div>

            <!-- 床位列表 -->
            <div class="bed-list">
              <el-empty
                v-if="!loadingBeds[ward._id] && (!wardBeds[ward._id] || wardBeds[ward._id].length === 0)"
                description="暂无床位"
                :image-size="80"
              />
              
              <div
                v-else
                v-loading="loadingBeds[ward._id]"
                class="bed-grid"
              >
                <div
                  v-for="bed in wardBeds[ward._id]"
                  :key="bed._id"
                  class="bed-item"
                  :class="{ 'occupied': bed.deviceId }"
                >
                  <div class="bed-header">
                    <span class="bed-number">{{ bed.bedNumber }}床</span>
                    <el-tag
                      :type="bed.deviceId ? 'success' : 'info'"
                      size="small"
                    >
                      {{ bed.deviceId ? '已占用' : '空闲' }}
                    </el-tag>
                  </div>
                  
                  <div v-if="bed.device" class="bed-device">
                    <div class="device-info">
                      <el-icon><Monitor /></el-icon>
                      <span>{{ bed.device.deviceName || bed.device.deviceId }}</span>
                    </div>
                    <el-tag
                      :type="bed.device.status === 'online' ? 'success' : 'info'"
                      size="small"
                    >
                      {{ bed.device.status === 'online' ? '在线' : '离线' }}
                    </el-tag>
                  </div>

                  <div class="bed-actions">
                    <el-button
                      v-if="!bed.deviceId"
                      link
                      type="primary"
                      size="small"
                      @click="handleBindDevice(ward, bed)"
                    >
                      绑定设备
                    </el-button>
                    <el-button
                      v-else
                      link
                      type="warning"
                      size="small"
                      @click="handleUnbindDevice(ward, bed)"
                    >
                      解绑设备
                    </el-button>
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click="handleEditBed(ward, bed)"
                    >
                      编辑
                    </el-button>
                    <el-button
                      link
                      type="danger"
                      size="small"
                      @click="handleDeleteBed(ward, bed)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="pagination.total > 0" class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑病房对话框 -->
    <el-dialog
      v-model="wardDialogVisible"
      :title="wardDialogTitle"
      width="500px"
      @close="handleWardDialogClose"
    >
      <el-form
        ref="wardFormRef"
        :model="wardForm"
        :rules="wardRules"
        label-width="100px"
      >
        <el-form-item label="病房名称" prop="wardName">
          <el-input
            v-model="wardForm.wardName"
            placeholder="请输入病房名称"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="病房编号" prop="wardNumber">
          <el-input
            v-model="wardForm.wardNumber"
            placeholder="请输入病房编号"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="楼栋" prop="building">
          <el-input
            v-model="wardForm.building"
            placeholder="请输入楼栋"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input
            v-model="wardForm.floor"
            placeholder="请输入楼层"
            maxlength="10"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="wardForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="wardDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleWardSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑床位对话框 -->
    <el-dialog
      v-model="bedDialogVisible"
      :title="bedDialogTitle"
      width="500px"
      @close="handleBedDialogClose"
    >
      <el-form
        ref="bedFormRef"
        :model="bedForm"
        :rules="bedRules"
        label-width="100px"
      >
        <el-form-item label="床位号" prop="bedNumber">
          <el-input
            v-model="bedForm.bedNumber"
            placeholder="请输入床位号"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="床位名称" prop="bedName">
          <el-input
            v-model="bedForm.bedName"
            placeholder="请输入床位名称（可选）"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="bedForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bedDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBedSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 绑定设备对话框 -->
    <el-dialog
      v-model="bindDialogVisible"
      title="绑定设备"
      width="500px"
      @close="handleBindDialogClose"
    >
      <el-form label-width="100px">
        <el-form-item label="选择设备">
          <el-select
            v-model="selectedDeviceId"
            placeholder="请选择设备"
            filterable
            style="width: 100%"
            @visible-change="handleDeviceSelectVisible"
          >
            <el-option
              v-for="device in availableDevices"
              :key="device.deviceId"
              :label="`${device.deviceName || device.deviceId} (${device.status === 'online' ? '在线' : '离线'})`"
              :value="device.deviceId"
            >
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span>{{ device.deviceName || device.deviceId }}</span>
                <el-tag
                  :type="device.status === 'online' ? 'success' : 'info'"
                  size="small"
                >
                  {{ device.status === 'online' ? '在线' : '离线' }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bindDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBindSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  Refresh,
  Edit,
  Delete,
  OfficeBuilding,
  Grid,
  User,
  Monitor
} from '@element-plus/icons-vue'
import {
  getWardList,
  getWardBeds,
  createWard,
  updateWard,
  deleteWard,
  createBed,
  updateBed,
  deleteBed,
  bindDeviceToBed,
  unbindDeviceFromBed
} from '@/api/ward'
import { getDeviceList } from '@/api/device'

// 搜索
const searchText = ref('')

// 加载状态
const loading = ref(false)
const loadingBeds = reactive({})

// 病房列表
const wardList = ref([])
const wardBeds = reactive({})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 统计数据
const wardStats = computed(() => {
  const stats = {
    totalWards: wardList.value.length,
    totalBeds: 0,
    occupiedBeds: 0
  }
  
  wardList.value.forEach(ward => {
    stats.totalBeds += ward.bedCount || 0
    stats.occupiedBeds += ward.occupiedCount || 0
  })
  
  return stats
})

// 病房对话框
const wardDialogVisible = ref(false)
const wardDialogTitle = computed(() => wardForm._id ? '编辑病房' : '添加病房')
const wardFormRef = ref(null)
const wardForm = reactive({
  _id: '',
  wardName: '',
  wardNumber: '',
  building: '',
  floor: '',
  description: ''
})
const wardRules = {
  wardName: [
    { required: true, message: '请输入病房名称', trigger: 'blur' }
  ]
}

// 床位对话框
const bedDialogVisible = ref(false)
const bedDialogTitle = computed(() => bedForm._id ? '编辑床位' : '添加床位')
const bedFormRef = ref(null)
const currentWard = ref(null)
const bedForm = reactive({
  _id: '',
  bedNumber: '',
  bedName: '',
  description: ''
})
const bedRules = {
  bedNumber: [
    { required: true, message: '请输入床位号', trigger: 'blur' }
  ]
}

// 绑定设备对话框
const bindDialogVisible = ref(false)
const currentBed = ref(null)
const selectedDeviceId = ref('')
const availableDevices = ref([])

// 获取病房列表
const fetchWardList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize
    }
    if (searchText.value) {
      params.search = searchText.value
    }
    
    const res = await getWardList(params)
    if (res.code === 200) {
      wardList.value = res.data.list
      pagination.total = res.data.total
      
      // 获取每个病房的床位
      wardList.value.forEach(ward => {
        fetchWardBeds(ward._id)
      })
    }
  } catch (error) {
    ElMessage.error('获取病房列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取病房床位
const fetchWardBeds = async (wardId) => {
  try {
    loadingBeds[wardId] = true
    const res = await getWardBeds(wardId)
    if (res.code === 200) {
      wardBeds[wardId] = res.data
    }
  } catch (error) {
    console.error('获取床位列表失败:', error)
  } finally {
    loadingBeds[wardId] = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchWardList()
}

// 分页
const handleSizeChange = () => {
  fetchWardList()
}

const handlePageChange = () => {
  fetchWardList()
}

// 添加病房
const handleAddWard = () => {
  resetWardForm()
  wardDialogVisible.value = true
}

// 编辑病房
const handleEditWard = (ward) => {
  Object.assign(wardForm, {
    _id: ward._id,
    wardName: ward.wardName,
    wardNumber: ward.wardNumber || '',
    building: ward.building || '',
    floor: ward.floor || '',
    description: ward.description || ''
  })
  wardDialogVisible.value = true
}

// 删除病房
const handleDeleteWard = async (ward) => {
  try {
    await ElMessageBox.confirm(
      '删除病房后将无法恢复，确定要删除吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await deleteWard(ward._id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchWardList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 提交病房表单
const handleWardSubmit = async () => {
  try {
    await wardFormRef.value.validate()
    
    const data = {
      wardName: wardForm.wardName,
      wardNumber: wardForm.wardNumber,
      building: wardForm.building,
      floor: wardForm.floor,
      description: wardForm.description
    }
    
    let res
    if (wardForm._id) {
      res = await updateWard(wardForm._id, data)
    } else {
      res = await createWard(data)
    }
    
    if (res.code === 200) {
      ElMessage.success(wardForm._id ? '更新成功' : '创建成功')
      wardDialogVisible.value = false
      fetchWardList()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    if (error !== false) {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }
}

// 关闭病房对话框
const handleWardDialogClose = () => {
  resetWardForm()
  wardFormRef.value?.clearValidate()
}

// 重置病房表单
const resetWardForm = () => {
  Object.assign(wardForm, {
    _id: '',
    wardName: '',
    wardNumber: '',
    building: '',
    floor: '',
    description: ''
  })
}

// 添加床位
const handleAddBed = (ward) => {
  currentWard.value = ward
  resetBedForm()
  bedDialogVisible.value = true
}

// 编辑床位
const handleEditBed = (ward, bed) => {
  currentWard.value = ward
  Object.assign(bedForm, {
    _id: bed._id,
    bedNumber: bed.bedNumber,
    bedName: bed.bedName || '',
    description: bed.description || ''
  })
  bedDialogVisible.value = true
}

// 删除床位
const handleDeleteBed = async (ward, bed) => {
  try {
    await ElMessageBox.confirm(
      '删除床位后将无法恢复，确定要删除吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await deleteBed(ward._id, bed._id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchWardBeds(ward._id)
      fetchWardList() // 更新统计
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 提交床位表单
const handleBedSubmit = async () => {
  try {
    await bedFormRef.value.validate()
    
    const data = {
      bedNumber: bedForm.bedNumber,
      bedName: bedForm.bedName,
      description: bedForm.description
    }
    
    let res
    if (bedForm._id) {
      res = await updateBed(currentWard.value._id, bedForm._id, data)
    } else {
      res = await createBed(currentWard.value._id, data)
    }
    
    if (res.code === 200) {
      ElMessage.success(bedForm._id ? '更新成功' : '创建成功')
      bedDialogVisible.value = false
      fetchWardBeds(currentWard.value._id)
      fetchWardList() // 更新统计
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    if (error !== false) {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }
}

// 关闭床位对话框
const handleBedDialogClose = () => {
  resetBedForm()
  bedFormRef.value?.clearValidate()
  currentWard.value = null
}

// 重置床位表单
const resetBedForm = () => {
  Object.assign(bedForm, {
    _id: '',
    bedNumber: '',
    bedName: '',
    description: ''
  })
}

// 绑定设备
const handleBindDevice = (ward, bed) => {
  currentWard.value = ward
  currentBed.value = bed
  selectedDeviceId.value = ''
  bindDialogVisible.value = true
}

// 解绑设备
const handleUnbindDevice = async (ward, bed) => {
  try {
    await ElMessageBox.confirm(
      '确定要解绑设备吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await unbindDeviceFromBed(ward._id, bed._id)
    if (res.code === 200) {
      ElMessage.success('解绑成功')
      fetchWardBeds(ward._id)
      fetchWardList() // 更新统计
    } else {
      ElMessage.error(res.message || '解绑失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('解绑失败')
      console.error(error)
    }
  }
}

// 获取可用设备列表
const handleDeviceSelectVisible = async (visible) => {
  if (visible && availableDevices.value.length === 0) {
    try {
      const res = await getDeviceList({ page: 1, pageSize: 1000 })
      if (res.code === 200) {
        availableDevices.value = res.data.list
      }
    } catch (error) {
      ElMessage.error('获取设备列表失败')
      console.error(error)
    }
  }
}

// 提交绑定
const handleBindSubmit = async () => {
  if (!selectedDeviceId.value) {
    ElMessage.warning('请选择设备')
    return
  }
  
  try {
    const res = await bindDeviceToBed(
      currentWard.value._id,
      currentBed.value._id,
      selectedDeviceId.value
    )
    if (res.code === 200) {
      ElMessage.success('绑定成功')
      bindDialogVisible.value = false
      fetchWardBeds(currentWard.value._id)
      fetchWardList() // 更新统计
    } else {
      ElMessage.error(res.message || '绑定失败')
    }
  } catch (error) {
    ElMessage.error('绑定失败')
    console.error(error)
  }
}

// 关闭绑定对话框
const handleBindDialogClose = () => {
  selectedDeviceId.value = ''
  currentWard.value = null
  currentBed.value = null
}

// 初始化
onMounted(() => {
  fetchWardList()
})
</script>

<style scoped lang="scss">
.ward-management-page {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  .stat-content {
    display: flex;
    align-items: center;
    gap: 20px;

    .stat-icon {
      width: 70px;
      height: 70px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;

      &.total {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.beds {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }

      &.occupied {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
    }

    .stat-info {
      flex: 1;

      .stat-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }

      .stat-value {
        font-size: 28px;
        font-weight: bold;
        color: #303133;
      }
    }
  }
}

.ward-list-card {
  .toolbar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .toolbar-left {
      display: flex;
      gap: 10px;
    }

    .toolbar-right {
      display: flex;
      gap: 10px;
    }
  }

  .ward-list {
    .ward-item {
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .ward-card {
      .ward-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 15px;
        border-bottom: 1px solid #ebeef5;
        margin-bottom: 15px;

        .ward-info {
          flex: 1;

          .ward-name {
            font-size: 18px;
            font-weight: bold;
            margin: 0 0 10px 0;
            display: flex;
            align-items: center;
            gap: 8px;
            color: #303133;
          }

          .ward-details {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 14px;
            color: #606266;

            .bed-stats {
              margin-left: 10px;
              color: #409eff;
              font-weight: 500;
            }
          }
        }

        .ward-actions {
          display: flex;
          gap: 8px;
        }
      }

      .bed-list {
        .bed-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
          gap: 15px;

          .bed-item {
            border: 2px solid #e4e7ed;
            border-radius: 8px;
            padding: 15px;
            transition: all 0.3s;
            background: #f9fafc;

            &:hover {
              border-color: #409eff;
              box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.2);
            }

            &.occupied {
              background: linear-gradient(135deg, #e8f4ff 0%, #f0f9ff 100%);
              border-color: #b3d8ff;
            }

            .bed-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 12px;

              .bed-number {
                font-size: 16px;
                font-weight: bold;
                color: #303133;
              }
            }

            .bed-device {
              margin-bottom: 12px;
              padding: 10px;
              background: white;
              border-radius: 6px;
              border: 1px solid #e4e7ed;

              .device-info {
                display: flex;
                align-items: center;
                gap: 8px;
                margin-bottom: 8px;
                font-size: 14px;
                color: #606266;

                .el-icon {
                  color: #409eff;
                }
              }
            }

            .bed-actions {
              display: flex;
              gap: 8px;
              flex-wrap: wrap;
            }
          }
        }
      }
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style>

